﻿/**
 * ...
 * @author sminutoli
 */
import com.dmotiko.meip.*
import mx.transitions.easing.*;
import mx.transitions.*;
 
class com.dmotiko.meip.SoundSection extends com.dmotiko.meip.Section
{
	
	private var mcController:MovieClip;
	private var mcPlay:ButtonClip;
	private var mcStop:ButtonClip;
	private var bPaused:Boolean;
	private var music:Sound;
	private var oSound:Object;
	private var nLastPosition:Number;
	private var musicCheck:MovieClip;
	
	private function initClip():Void {
		super.initClip();
		_alpha = 0;
		_visible = false;
		
		oSound = new Object();
		oSound.volume = 0;
		
		nLastPosition = 0;
		
		var root = this;
		
		var sMusic = "music.mp3";
		if ( _root["music_src"] ) sMusic = _root["music_src"];
		
		music = new Sound();
		music.loadSound(sMusic);
		music.onLoad = function() {
			this.setVolume(0);
			root.show();
			//Site.getApp().log( "SoundSection | music.onLoad" );
			Site.getApp().setSound(true);
		}
						
		music.onSoundComplete = function() {
			//Site.getApp().log( "SoundSection | music.onSoundComplete" );
			this.start(0);
		}
		
		Site.getApp().addEventListener( WebSite.SOUND_CHANGED, Delegate.create( this, sound_changed ) );
	}
	
	function childLoaded( e ):Void {
		
		if ( e.target == mcPlay ) {
			mcPlay.addEventListener( BaseClipEvent.CHANGED, Delegate.create(this, toggle_snd) );
						
		} else if ( e.target == mcStop) {
			mcStop.addEventListener( BaseClipEvent.CHANGED, Delegate.create(this, toggle_snd) );
			
		}
	}
	
	private function toggle_snd( e ):Void {
		if ( e.target == mcPlay) {
			Site.getApp().setSound(true);
			
		} else {
			Site.getApp().setSound(false);
			
		}
	}
	
	private function sound_changed(e):Void 
	{
		if ( Site.getApp().getSound() ) {
			mcStop.setActive(false, true);
			mcPlay.onRollOver();
			mcPlay.setActive(true, true);
			pauseMusic(false);
			
		} else {
			mcPlay.setActive(false, true);
			mcStop.onRollOver();
			mcStop.setActive(true, true);
			pauseMusic(true);
			
		}
	}
	
	public function pauseMusic(b:Boolean, watch:Object):Void {
		bPaused = b;
		if (b) {
			registerTween( "fadeSound", new Tween( oSound, "volume", None.easeOut, oSound.volume, 0, 2, true), false, true, true);
			
		} else {
			music.start( nLastPosition / 1000 );
			registerTween( "fadeSound", new Tween( oSound, "volume", None.easeOut, oSound.volume, 100, 2, true), false, true, true);
		}		
	}
	
	private function tweenChanged(key, tween):Void {
		music.setVolume( oSound.volume );
	}
	private function tweenFinished(key, tween):Void {
		if ( oSound.volume == 0 ) {
			nLastPosition = music.position;
			music.stop();
		}
	}
	
}